package com.wewins.fota.service;

import com.alibaba.fastjson.JSONObject;
import com.wewins.fota.bean.bo.SysLog;
import com.wewins.fota.common.constant.RedisConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
public class SysLogService {
    private final RedisTemplate<String, String> template;

    public SysLogService(RedisTemplate<String, String> template) {
        this.template = template;
    }

    public List<SysLog> queryAll() {
        List<SysLog> sysLogs = new ArrayList<>();
        Set<String> keys = template.keys(RedisConst.REDIS_KEY_SYS_LOG + ":*");
        if (keys != null) {
            keys.forEach(item -> {
                template.opsForHash().entries(item)
                        .forEach((key, val) -> sysLogs.add(JSONObject.parseObject((String) val, SysLog.class)));
            });
        }

        return sysLogs;
    }

    public File download(String fileName) {
        Object val = template.opsForHash().get(RedisConst.REDIS_KEY_SYS_LOG + ":management", fileName);
        if (val != null) {
            return new File(JSONObject.parseObject((String) val, SysLog.class).getFullPath());
        }
        return null;
    }

}
